package cron

import (
	"bigdevops/src/common"
	"bigdevops/src/models"
	"encoding/json"
	"fmt"
	"github.com/prometheus/alertmanager/template"
	"go.uber.org/zap"
	"time"
)

var (
	// 群和私聊共用的 json
	feiShuCardContent = `
{
  "elements": [
    {
      "tag": "div",
      "fields": [
        {
          "is_short": true,
          "text": {
            "tag": "lark_md",
            "content": "%s"
          }
        },
        {
          "is_short": true,
          "text": {
            "tag": "lark_md",
            "content": "%s"
          }
        }
      ]
    },
    {
      "tag": "div",
      "fields": [
        {
          "is_short": true,
          "text": {
            "tag": "lark_md",
            "content": "%s"
          }
        },
        {
          "is_short": true,
          "text": {
            "tag": "lark_md",
            "content": "%s"
          }
        }
      ]
    },
    {
      "tag": "column_set",
      "flex_mode": "none",
      "background_style": "default",
      "columns": [
        {
          "tag": "column",
          "width": "weighted",
          "weight": 1,
          "vertical_align": "top",
          "elements": [
            {
              "tag": "div",
              "text": {
                "content": "%s",
                "tag": "lark_md"
              }
            }
          ]
        },
        {
          "tag": "column",
          "width": "weighted",
          "weight": 1,
          "vertical_align": "top",
          "elements": [
            {
              "tag": "div",
              "text": {
                "content": "%s",
                "tag": "lark_md"
              }
            }
          ]
        }
      ]
    },
    {
      "tag": "column_set",
      "flex_mode": "none",
      "background_style": "default",
      "columns": [
        {
          "tag": "column",
          "width": "weighted",
          "weight": 1,
          "vertical_align": "top",
          "elements": [
            {
              "tag": "div",
              "text": {
                "content": "%s",
                "tag": "lark_md"
              }
            }
          ]
        },
        {
          "tag": "column",
          "width": "weighted",
          "weight": 1,
          "vertical_align": "top",
          "elements": [
            {
              "tag": "markdown",
              "content": "%s"
            }
          ]
        }
      ]
    },
    {
      "tag": "div",
      "fields": [
        {
          "is_short": true,
          "text": {
            "tag": "lark_md",
            "content": "%s\n"
          }
        },
        {
          "is_short": true,
          "text": {
            "tag": "lark_md",
            "content": "%s"
          }
        }
      ]
    },
    {
      "tag": "hr"
    },
    {
      "tag": "markdown",
      "content": "%s"
    },
    {
      "tag": "column_set",
      "flex_mode": "none",
      "background_style": "default",
      "columns": []
    },
    {
      "tag": "hr"
    },
    {
      "tag": "div",
      "text": {
        "tag": "lark_md",
        "content": "🔴 告警屏蔽按钮 [下面是单一告警屏蔽👇][右侧是按告警名称屏蔽👉]"
      },
      "extra": {
        "tag": "overflow",
        "options": [
          {
            "text": {
              "tag": "plain_text",
              "content": "屏蔽1小时"
            },
            "value": "appStore",
            "url": "%s"
          },
          {
            "text": {
              "tag": "plain_text",
              "content": "屏蔽6小时"
            },
            "value": "document",
            "url": "%s"
          },
          {
            "text": {
              "tag": "plain_text",
              "content": "屏蔽24小时"
            },
            "value": "document",
            "url": "%s"
          }
        ]
      }
    },
    {
      "tag": "action",
      "actions": [
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "认领告警"
          },
          "type": "primary",
          "multi_url": {
            "url": "%s",
            "android_url": "",
            "ios_url": "",
            "pc_url": ""
          },
          "confirm": {
            "title": {
              "tag": "plain_text",
              "content": "确定认领吗"
            },
            "text": {
              "tag": "plain_text",
              "content": ""
            }
          }
        },
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "屏蔽1小时"
          },
          "type": "default",
          "multi_url": {
            "url": "%s",
            "android_url": "",
            "ios_url": "",
            "pc_url": ""
          },
          "confirm": {
            "title": {
              "tag": "plain_text",
              "content": "确定屏蔽吗"
            },
            "text": {
              "tag": "plain_text",
              "content": ""
            }
          }
        },
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "屏蔽24小时"
          },
          "type": "danger",
          "multi_url": {
            "url": "%s",
            "android_url": "",
            "ios_url": "",
            "pc_url": ""
          },
          "confirm": {
            "title": {
              "tag": "plain_text",
              "content": "确定屏蔽吗"
            },
            "text": {
              "tag": "plain_text",
              "content": ""
            }
          }
        }
      ]
    },
    {
      "tag": "hr"
    },
    {
      "tag": "action",
      "actions": [
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "取消屏蔽"
          },
          "type": "primary",
          "multi_url": {
            "url": "%s",
            "android_url": "",
            "ios_url": "",
            "pc_url": ""
          },
          "confirm": {
            "title": {
              "tag": "plain_text",
              "content": "确定取消吗"
            },
            "text": {
              "tag": "plain_text",
              "content": ""
            }
          }
        },
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "屏蔽6小时"
          },
          "type": "default",
          "multi_url": {
            "url": "%s",
            "android_url": "",
            "ios_url": "",
            "pc_url": ""
          },
          "confirm": {
            "title": {
              "tag": "plain_text",
              "content": "确定屏蔽吗"
            },
            "text": {
              "tag": "plain_text",
              "content": ""
            }
          }
        },
        {
          "tag": "button",
          "text": {
            "tag": "plain_text",
            "content": "屏蔽7天"
          },
          "type": "danger",
          "multi_url": {
            "url": "%s",
            "android_url": "",
            "ios_url": "",
            "pc_url": ""
          },
          "confirm": {
            "title": {
              "tag": "plain_text",
              "content": "确定屏蔽吗"
            },
            "text": {
              "tag": "plain_text",
              "content": ""
            }
          }
        }
      ]
    },
    {
      "tag": "hr"
    },
    {
      "tag": "div",
      "text": {
        "content": "\ud83d\ude4b\ud83c\udffc [\u6211\u8981\u53cd\u9988\u8bef\u62a5](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message-development-tutorial/introduction?from=mcb) | \ud83d\udcdd [\u5f55\u5165\u62a5\u8b66\u5904\u7406\u8fc7\u7a0b](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message-development-tutorial/introduction?from=mcb)",
        "tag": "lark_md"
      }
    }
  ],
  "header": {
    "template": "%s",
    "title": {
      "content": "%s",
      "tag": "plain_text"
    }
  },
  "card_link": {
    "url": "",
    "pc_url": "",
    "android_url": "",
    "ios_url": ""
  }
}
`
	// 群聊要在 上面基础上封装 card
	feiShuCartDataQun = `

{
        "msg_type": "interactive",
        "card":  %s
}`
)

func (ac *AlertCache) GenerateFeishuCardContentOneAlert(alert template.Alert, event *models.MonitorAlertEvent, rule *models.MonitorAlertRule, sendGroup *models.MonitorSendGroup) {
	//msg := fmt.Sprintf(feiShuCardJsonMsg, common.GenJsonString(alert.Labels[common.MONITOR_ALERT_NAME_KEY]+alert.Fingerprint))
	//msgQun := fmt.Sprintf(feiShuCartDataQun, alert.Labels[common.MONITOR_ALERT_NAME_KEY]+alert.Fingerprint)

	// 告警的title
	alertHeader := fmt.Sprintf("[触发次数:%v]告警标题:%s ：当前值 %s",
		event.EventTimes,
		alert.Labels[common.MONITOR_ALERT_NAME_KEY],
		alert.Annotations[common.MONITOR_RULE_ANNO_VALUE],
	)
	severity := alert.Labels[common.MONITOR_ALERT_SEVERITY_KEY]
	streeNode := alert.Labels[common.MONITOR_ALERT_BIND_NODE_KEY]

	alertHeaderColor := common.MONITOR_ALERT_SEVERITY_TITLE_COLOR_MAP[severity]

	// 告警级别 **🌡️告警级别：**\n报事报修
	msgSeverity := fmt.Sprintf(`**🌡️告警级别：**\n%s`, severity)
	msgStatus := fmt.Sprintf(`**📝当前状态：**\n<font color='%s'>%s</font>`, common.MONITOR_ALERT_STATUS_COLOR_MAP[alert.Status], common.MONITOR_ALERT_STATUS_CH_MAP[alert.Status])
	msgStreeNode := fmt.Sprintf(`**🏝️ 绑定的服务树：**\n<font color='green'>%s</font>\n`, streeNode)
	msgTime := fmt.Sprintf(`**🕐 触发时间：**\n%s`, alert.StartsAt.Format("2006-01-02 15:04:05"))

	var msgGrafana, msgExpr string
	if rule != nil {
		msgGrafana = fmt.Sprintf(`**🗳查看grafana大盘图**\n[链接地址](%s)`, rule.GrafanaLink)
		msgExpr = fmt.Sprintf(`**🏹修改告警规则**  [规则地址](%s)\n<font color='red'>%s</font>`,
			fmt.Sprintf("%s/%s?ruleid=%v",
				ac.Sc.FrontDomain,
				"monitor/rule/detail",
				rule.ID),
			rule.Expr,
		)
	}

	// 私聊 userId 列表
	siliaoUserIds := map[string]string{}

	// 获取值班组 信息
	msgOnduty := "值班组和值班人信息(出现这个说明值班信息获取有问题)"
	yuanshiRen := ""
	onDutyGroup := ac.GetOndutyGroupById(sendGroup.OnDutyGroupId)
	onDutyGroupUrl := fmt.Sprintf("%s/%s?id=%v",
		ac.Sc.FrontDomain,
		"monitor/onduty/detail",
		onDutyGroup.ID)
	if onDutyGroup != nil {

		onDutyGroup.FillTodayOnDutyUser()
		if onDutyGroup.TodayDutyUser != nil {
			yuanshiRen = onDutyGroup.TodayDutyUser.RealName
			msgOnduty = fmt.Sprintf(`**👨‍💻 值班组 [%s](%s)：**\n当日值班人:%s\n user_id=%s<at id=%s></at>`,
				onDutyGroup.Name,
				onDutyGroupUrl,
				onDutyGroup.TodayDutyUser.RealName,
				onDutyGroup.TodayDutyUser.FeiShuUserId,
				onDutyGroup.TodayDutyUser.FeiShuUserId,
			)
			siliaoUserIds[onDutyGroup.TodayDutyUser.FeiShuUserId] = ""
		}

	}

	msgUpgrade := `**🎛️ 升级状态：**\n未升级`
	// 判断告警升级
	if event.Status != common.MONITOR_ALERT_STATUS_RENLING && alert.Status == common.MONITOR_ALERT_STATUS_FIRING && sendGroup.FirstUpgradeUsers != nil && len(sendGroup.FirstUpgradeUsers) > 0 {
		// 判断时间  当前时间 - 第一次触发时间  > upgrade间隔
		if sendGroup.UpgradeMinutes == 0 {
			sendGroup.UpgradeMinutes = 30
		}
		if time.Now().Sub(alert.StartsAt) > time.Minute*time.Duration(sendGroup.UpgradeMinutes) {

			upgradeUserNames := ``
			upgradeUserAtIds := ``
			for _, user := range sendGroup.FirstUpgradeUsers {
				user := user
				siliaoUserIds[user.FeiShuUserId] = ""
				upgradeUserNames = fmt.Sprintf("%s %s", upgradeUserNames, user.RealName)
				upgradeUserAtIds = fmt.Sprintf("%s <at id=%s></at> ", upgradeUserAtIds, user.FeiShuUserId)
			}

			msgUpgrade = fmt.Sprintf(`**🎛️ 升级状态：**\n**<font color='red'>已升级</font>** [接收人变化]\n[由 %s] -->[%s] `,

				yuanshiRen,
				upgradeUserNames,
			)
			// 群里at 人得变化
			msgOnduty = fmt.Sprintf(`**👨‍💻 值班组 [%s](%s)：**\n   告警升级接收人: %s`,
				onDutyGroup.Name,
				onDutyGroupUrl,
				upgradeUserAtIds,
			)
			event.Status = common.MONITOR_ALERT_STATUS_UPGRADED
			event.UpdateOne()

		}

	}
	//log.Printf("判断认领:%+v %+v", event.RenLingUser, event)
	// 判断认领
	if event.RenLingUser != nil {
		// 群里at 人得变化
		msgOnduty = fmt.Sprintf(`**👨‍💻 值班组 [%s](%s)：**\n认领人:%s\n user_id=%s<at id=%s></at>`,
			onDutyGroup.Name,
			onDutyGroupUrl,
			event.RenLingUser.RealName,
			event.RenLingUser.FeiShuUserId,
			event.RenLingUser.FeiShuUserId,
		)
	}

	// 处理告警标签
	labelMap := alert.Labels
	delete(labelMap, common.MONITOR_ALERT_NAME_KEY)
	delete(labelMap, common.MONITOR_ALERT_SEVERITY_KEY)
	delete(labelMap, common.MONITOR_ALERT_BIND_NODE_KEY)
	delete(labelMap, common.MONITOR_ALERT_RULE_KEY)
	delete(labelMap, common.MONITOR_ALERT_MATCH_KEY)

	anno := alert.Annotations
	delete(anno, common.MONITOR_RULE_ANNO_VALUE)

	msgLabel := fmt.Sprintf(`**🛶标签信息：**\n%s`, common.GenKvStringByMap(labelMap))
	msgAnno := fmt.Sprintf(`**🚂anno信息：**\n%s`, common.GenKvStringByMap(anno))

	msgSendGroup := "发送组"
	sendGroupUrl := fmt.Sprintf("%s/%s?id=%v",
		ac.Sc.FrontDomain,
		"monitor/sendgroup/detail",
		sendGroup.ID)
	msgSendGroup = fmt.Sprintf(`**📝修改发送组：**\n[%s](%s)`,

		sendGroup.Name,
		sendGroupUrl,
	)

	msgRenlingUrl := fmt.Sprintf("%s/%s?fingerprint=%v",
		ac.Sc.BackendDomain,
		"renling",
		alert.Fingerprint,
	)
	msgSilenceOneHourUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=1",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)

	msgSilence1HourByNameUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=1&by_name=1",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)
	msgSilence6HourByNameUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=6&by_name=1",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)
	msgSilence24HourByNameUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=24&by_name=1",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)

	msgSilence24HourUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=24",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)

	msgSilenceCancelUrl := fmt.Sprintf("%s/%s?fingerprint=%v",
		ac.Sc.BackendDomain,
		"unsilence",
		alert.Fingerprint,
	)

	msgSilence6HourUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=6",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)

	msgSilence7DayUrl := fmt.Sprintf("%s/%s?fingerprint=%v&hour=168",
		ac.Sc.BackendDomain,
		"silence",
		alert.Fingerprint,
	)
	msgSi := fmt.Sprintf(feiShuCardContent,
		msgLabel,
		msgAnno,
		msgSeverity,
		msgStatus,
		msgStreeNode,
		msgTime,
		msgUpgrade,
		msgOnduty,
		msgGrafana,
		msgSendGroup,
		msgExpr,
		msgSilence1HourByNameUrl,
		msgSilence6HourByNameUrl,
		msgSilence24HourByNameUrl,
		msgRenlingUrl,
		msgSilenceOneHourUrl,
		msgSilence24HourUrl,

		msgSilenceCancelUrl,
		msgSilence6HourUrl,
		msgSilence7DayUrl,

		alertHeaderColor,
		alertHeader,
	)

	//msg := fmt.Sprintf(feiShuCardQunMsg, "1 级报警 - 数据平台：当前值 xxxx")
	//fmt.Println(msg)

	//私聊发送
	ac.SentFeishuSiLiao(msgSi, siliaoUserIds)

	// 群聊发送
	msgQun := fmt.Sprintf(feiShuCartDataQun, msgSi)
	ac.SentFeishuQunLiao(msgQun, sendGroup.FeishuQunRobotToken)
}

func (ac *AlertCache) SentFeishuQunLiao(msg string, rebotToken string) {

	url := fmt.Sprintf("%s/%s", ac.Sc.ImFeishuC.QunLiaoMessageApi, rebotToken)
	emptyMap := map[string]string{}
	bodyBytes, err := common.PostWithJsonString(ac.Sc.Logger, "SentFeishu", ac.Sc.ImFeishuC.RequestTimeoutSeconds, url, msg, emptyMap, emptyMap)
	if err != nil {
		ac.Sc.Logger.Error("发送飞书群聊卡片消息失败",
			zap.Error(err),
			zap.Any("结果", string(bodyBytes)),
		)
	}

}

// 私聊的
type FeishuPrivateCardMsg struct {
	MsgType   string `json:"msg_type"`
	ReceiveId string `json:"receive_id"`
	// 要求content已经 jsonString
	Content string `json:"content"`
}

func (ac *AlertCache) SentFeishuSiLiao(cardContent string, siliaoUserIds map[string]string) {

	for userId := range siliaoUserIds {
		// TODO 去掉 mockid
		userId = "6d31gdf4"

		params := map[string]string{"receive_id_type": "user_id"}
		//tenantAccessToken := "t-g104bcaOOP4OKPYXEJ673WWQGMZ3UYGR3QARW7QA"
		tenantAccessToken := ac.GetSiLiaoRobotToken()
		headers := map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", tenantAccessToken),
			"Content-Type":  "application/json",
		}

		feishuPrivateCardMsg := FeishuPrivateCardMsg{
			MsgType:   "interactive",
			ReceiveId: userId,
			Content:   cardContent,
		}
		data, err := json.Marshal(feishuPrivateCardMsg)

		url := "https://open.feishu.cn/open-apis/im/v1/messages"
		bodyBytes, err := common.PostWithJsonString(ac.Sc.Logger, "SentFeishuPrivate", 2, url, string(data), params, headers)
		if err != nil {
			ac.Sc.Logger.Error("发送飞书私聊聊卡片消息失败",
				zap.Error(err),
				zap.Any("结果", string(bodyBytes)),
				zap.Any("userId", userId),
			)
		}
	}

}
